from django.conf.urls.defaults import url
from django.utils.decorators import wraps

def func_to_view(f, pass_request=True):
    @wraps(f)
    def _dec(request, *a, **kw):
        kwargs = dict(kw)
        for k, v in request.REQUEST.items():
            kwargs[str(k)] = v
        return f(request, *a, **kwargs)
    return _dec

## This may have been a good idea, but it doesn't work with the descriptor-based method dispatch approach.
# class urls(list):
#     def __getitem__(self, idx):
#         item = super(urls, self).__getitem__(idx)
#         if isinstance(item, FunctionType):
#             name = item.__name__
#             if hasattr(item, 'export_name'):
#                 name = item.export_name
#             if hasattr(self, 'instance'):
#                 item = types.MethodType(item, self.instance, self.instance.__class__)
#             return patterns('', (r'^%s/$' % name, item))
        
#     def export(self, func):
#         self.append(func)

#     def __get__(self, instance, owner):
#         # Bind the instance
#         self.instance = instance

class AjaxAPI(object):
    def url_patterns(self, prefix=''):
        attrs = ((name, getattr(self, name)) for name in dir(self)
                 if not name.startswith('__'))
        methods = ((name, method) for (name, method) in attrs if callable(method))

        res = []
        for name, method in methods:
            exported = getattr(method, 'exported', False)
            if not exported: continue
            if isinstance(exported, basestring):
                export_name = exported
            else:
                export_name = name # Default to exporting by function name
            res.append(url('^%s%s/$' % (prefix, export_name),
                           func_to_view(method)))
        return res

    @staticmethod
    def exported(f, name=True):
        f.exported = name
        return f
    
